package org.apollo.sqlite.sql.insert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apollo.sqlite.core.SqliteContext;
import org.apollo.sqlite.sql.ArgPair;

public class SqlInsert implements Insert {
	
	private StringBuilder sqlBuilder = new StringBuilder();

	private String tableName;

	public SqlInsert(String tableName) {
		this.tableName = tableName;
	}

	private InsertConst insert(Object[] args) {
		sqlBuilder.append("INSERT INTO " + tableName);
		StringBuilder whereBuilder = new StringBuilder(" (");
		StringBuilder valuesBuilder = new StringBuilder(" (");
		for (int i = 0; i < args.length; i += 2) {
			whereBuilder.append(SqliteContext.getColumn(String.valueOf(args[i]))).append(",");
			valuesBuilder.append(SqliteContext.getSqlValue(args[i + 1])).append(",");
		}
		whereBuilder.delete(whereBuilder.length() - 1, whereBuilder.length());
		valuesBuilder.delete(valuesBuilder.length() - 1, valuesBuilder.length());
		whereBuilder.append(")");
		valuesBuilder.append(")");
		sqlBuilder.append(whereBuilder).append(" VALUES").append(valuesBuilder);
		return new SqlInsertConst(sqlBuilder);
	}

	@Override
	public InsertConst insert(Map<String, Object> args) {
		if (args == null || args.size() < 1) {
			throw new IllegalArgumentException("insert args shoud not be null or empty ! ");
		}
		List<Object> objList = new ArrayList<>();
		for (String whereArg : args.keySet()) {
			objList.add(whereArg);
			objList.add(args.get(whereArg));
		}
		return insert(objList.toArray());
	}

	@Override
	public InsertConst insert(ArgPair argPair) {
		return insert(argPair.argPairMap);
	}
}
